﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MegavaniaX.World;

namespace MegavaniaX.Actors.States
{
    /// <summary>
    /// State machine class.
    /// </summary>
    public class StateMachine
    {
        /// <summary>
        /// Current state of the machine.
        /// </summary>
        private IState _state;

        public StateMachine(IState initialState)
        {
            _state = initialState;
        }

        public IState CurrentState
        {
            get
            {
                return _state;
            }
        }

        /// <summary>
        /// Updates the state machine.
        /// </summary>
        /// <param name="elapsedTime"></param>
        public void Update(TimeSpan elapsedTime, Screen screen)
        {
            bool didTransition = _state.Update(elapsedTime, screen);
            if (didTransition)
            {
                _state.OnExit();
                _state = _state.NextState;
                _state.OnEnter();
            }
        }

        /// <summary>
        /// Handles the given event, if possible.
        /// </summary>
        /// <param name="evt"></param>
        public void HandleEvent(IMegavaniaEvent evt)
        {
            if (_state.CanHandleEvent(evt.EventType))
            {
                bool didTransition = _state.HandleEvent(evt);
                if (didTransition)
                {
                    _state.OnExit();
                    _state = _state.NextState;
                    _state.OnEnter();
                }
            }
        }
    }
}
